package org.shangda.wechat.pet.web.controller.miniapp;

import com.alibaba.fastjson.JSONObject;
import org.shangda.wechat.pet.enums.ErrorCode;
import org.shangda.wechat.pet.service.MemberService;
import org.shangda.wechat.pet.util.AESUtil;
import org.shangda.wechat.pet.util.Constants;
import org.shangda.wechat.pet.web.vo.EncryptedRequest;
import org.shangda.wechat.pet.web.vo.MemberSimpleInfo;
import org.shangda.wechat.pet.web.vo.MiniappMemberVo;
import com.power.common.model.CommonResult;
import com.power.common.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 小程序会员相关接口
 */
@Slf4j
@RestController
@RequestMapping("miniapp/")
public class MiniappMemberController {
    @Resource
    private MemberService memberService;

    /**
     * 保存会员信息，包括新增和修改
     * @param miniappMemberVo
     * @return
     */
    @PostMapping("save_member")
    public CommonResult saveMember(@RequestBody MiniappMemberVo miniappMemberVo, @RequestAttribute(value = Constants.MINIAPP_MEMBER) MemberSimpleInfo memberSimpleInfo){
        log.info("doRegister miniappMemberVo : {}, id : {}", miniappMemberVo, memberSimpleInfo.getMemberId());
        if(null == miniappMemberVo.getMemberId()){
            miniappMemberVo.setMemberId(memberSimpleInfo.getMemberId());
        }
        return memberService.saveMember(miniappMemberVo);
    }

    /**
     * 解析用户信息，包括手机号
     * @param request
     * @param memberSimpleInfo
     * @return
     */
    @PostMapping("decodeUserInfo")
    public CommonResult<MiniappMemberVo> decodeUserInfo(@RequestBody EncryptedRequest request, @RequestAttribute(value = Constants.MINIAPP_MEMBER, required = true) MemberSimpleInfo memberSimpleInfo) {
        String result = decodeMemberInfo(request, memberSimpleInfo);
        log.info("用户解密数据:" + result);
        if (StringUtil.isNotEmpty(result)) {
            JSONObject jsonObject=null;
            MiniappMemberVo memberVo =new MiniappMemberVo();
            try{
                jsonObject=JSONObject.parseObject(result);
                if(null!=jsonObject){
                    memberVo.setUnionId(jsonObject.getString("unionId"));
                    memberVo.setNickname(jsonObject.getString("nickName"));
                    memberVo.setGender(jsonObject.getByte("gender"));
                    memberVo.setOpenId(jsonObject.getString("openId"));
                    memberVo.setCity(jsonObject.getString("city"));
                    memberVo.setProvince(jsonObject.getString("province"));
                    memberVo.setCountry(jsonObject.getString("country"));
                    memberVo.setHeadImgUrl(jsonObject.getString("avatarUrl"));
                    memberVo.setMobile(jsonObject.getString("phoneNumber"));
                    if(StringUtil.isNotEmpty(memberVo.getOpenId())) {
                        memberService.updateMemberByAuthorize(memberVo);
                    }
                    if(StringUtil.isNotEmpty(memberVo.getMobile())){
                        memberVo.setMobileSensitive(StringUtils.left(memberVo.getMobile(), 3).concat(StringUtils.removeStart(StringUtils.leftPad(StringUtils.right(memberVo.getMobile(), 4), StringUtils.length(memberVo.getMobile()), "*"), "***")));

                    }
                    return CommonResult.ok().setResult(memberVo);
                }
            }catch (Exception e){
                log.error("解密错误，无法转换对象",e);
                return CommonResult.fail(ErrorCode.MEMBER_DECODE_ERROR);
            }
        }
        return CommonResult.fail(ErrorCode.MEMBER_DECODE_ERROR);
    }

    /**
     * 解密加密字符串c
     * @param request
     * @param memberSimpleInfo
     * @return
     */
    private String decodeMemberInfo(EncryptedRequest request, MemberSimpleInfo memberSimpleInfo) {
        try{
            log.info("encryptedData:{}, iv : {}, sessionKey : {}", request.getEncryptedData(),request.getIv(), memberSimpleInfo.getSessionKey());
            return AESUtil.decrypt(Base64.decodeBase64(request.getEncryptedData()), Base64.decodeBase64(memberSimpleInfo.getSessionKey()), Base64.decodeBase64(request.getIv()));
        }
        catch (Exception e){
            return null;
        }
    }

    /**
     * 获取会员信息
     * @param memberSimpleInfo
     * @return
     */
    @GetMapping("member_info")
    public CommonResult<MiniappMemberVo> memberInfo(@RequestAttribute(value = Constants.MINIAPP_MEMBER, required = false) MemberSimpleInfo memberSimpleInfo){
        MiniappMemberVo miniappMemberVo = memberService.getMemberInfo(memberSimpleInfo);
        return CommonResult.ok().setResult(miniappMemberVo);
    }


    /**
     * 注销会员
     * @param memberSimpleInfo
     * @return
     */
    @GetMapping("member_cancellation")
    public CommonResult<MiniappMemberVo> memberCancellation(@RequestAttribute(value = Constants.MINIAPP_MEMBER, required = false) MemberSimpleInfo memberSimpleInfo){
        memberService.memberCancellation(memberSimpleInfo.getMemberId());
        return CommonResult.ok();
    }

    /**
     * 获取会员手机号
     * @param code
     * @return
     */
    @GetMapping("get_user_phone_number/{code}")
    public CommonResult<String> getUserPhoneNumber(@PathVariable("code")String code){
        return CommonResult.ok().setResult(memberService.getUserPhoneNumber(code));
    }
}
